package api

import (
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
	"turn-around/internal/models/dao"
	"turn-around/internal/models/services"
	"turn-around/internal/request"
	"turn-around/pkg"
)

func Register(c *gin.Context) {
	var req request.User
	err := c.ShouldBind(&req)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": http.StatusBadRequest,
			"msg":  "数据不能为空",
		})
		return
	}
	user := dao.User{
		Name:   req.Name,
		Mobile: req.Mobile,
		Code:   req.Code,
	}
	err = services.CreateUser(user)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": http.StatusBadRequest,
			"msg":  "注册失败",
		})
		return
	} else {
		c.JSON(http.StatusOK, gin.H{
			"code": http.StatusOK,
			"msg":  "注册成功",
		})
	}
}

func SendOut(c *gin.Context) {
	var req request.Send
	err := c.ShouldBind(&req)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": http.StatusBadRequest,
			"msg":  "数据不能为空",
		})
		return
	}
	pkg.Phone(req.Mobile)
	err = pkg.Send()
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": http.StatusBadRequest,
			"msg":  "短息发送失败",
		})
		return
	} else {
		c.JSON(http.StatusOK, gin.H{
			"code": http.StatusOK,
			"msg":  "短信发送成功",
		})
	}
}

func Login(c *gin.Context) {
	var req request.Login
	err := c.ShouldBind(&req)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": http.StatusBadRequest,
			"msg":  "数据不能为空",
		})
		return
	}
	user, err, _ := services.GetUserInfo(req.Mobile)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": http.StatusBadRequest,
			"msg":  "手机号错误",
		})
		return
	}
	if user.Code != req.Code {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": http.StatusBadRequest,
			"msg":  "验证码错误",
		})
		return
	}
	CustomClaims := pkg.CustomClaims{
		ID: user.ID,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().Unix() + 86400,
		},
	}
	token, _ := pkg.NewJWT("2208A").CreateToken(CustomClaims)
	c.JSON(http.StatusOK, gin.H{
		"code":  http.StatusOK,
		"msg":   "登录成功",
		"token": token,
	})
}
